package com.bestcem.xm.survey.util;


import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;

/**
 * @ClassName: DbSearcherSingleton
 * @Description: 双重检查方式 单例
 * @Author: chenglong.yue
 * @Date: 2023/2/7 15:01
 */
@Slf4j
public class DbSearcherSingleton {

    private DbSearcherSingleton() {
    }

    private static volatile Searcher singleton;

    public static Searcher getInstance() {
        if (singleton == null) {
            synchronized (Searcher.class) {
                if (singleton == null) {
                    try {
                        ClassPathResource resource = new ClassPathResource("ip2region.xdb");
                        //获取真实文件路径
                        String path = resource.getURL().getPath();
                        byte[] cBuff = Searcher.loadContentFromFile(path);
                        singleton = Searcher.newWithBuffer(cBuff);
                        log.info("加载了ip2region.xdb文件,Searcher初始化完成!");
                    } catch (Exception e) {
                        log.error("初始化ip2region.xdb文件失败,报错信息:[{}]", e.getMessage(), e);
                        throw new RuntimeException("系统异常!");
                    }
                }
            }
        }
        return singleton;
    }
}
